<?php


namespace app\manage\controller;

use other\MessageSend;
use other\SmsMuSend;
use other\SmsWYSend;
use think\Db;
use think\Log;
use app\common\model\PushRecord;

class Merchant extends Base
{
    const PUSH_SYSTEM_FENGZHU = 1; //推送到凤翥（默认）
    const PUSH_SYSTEM_MIAOYAN = 2; //推送到妙言
    const PUSH_SYSTEM_ZHANGDALONG = 3; // 推送到张达龙
    public $push_system_type = [
        self::PUSH_SYSTEM_FENGZHU => "凤翥",
        self::PUSH_SYSTEM_MIAOYAN => "妙言",
        self::PUSH_SYSTEM_ZHANGDALONG => "张达龙"
    ];

    // 推送系统数据
    public $push_system_mapping = [
        self::PUSH_SYSTEM_FENGZHU => [
            'api_url' => '',
            'api_name' => "",
            'rule_json' => "",
            'api_key' => ""
        ],
        self::PUSH_SYSTEM_MIAOYAN => [
            'api_url' => 'http://qwe.rty.uio.pas.chengjiao.icu/api/v1/cjPush',
            'api_name' => "新盘API",
            'rule_json' => '[{"orig":"clue_name","curr":"name","describe":""}]',
            'api_key' => "CommonClue"
        ],
        self::PUSH_SYSTEM_ZHANGDALONG => [
            'api_url' => 'http://crm.whjinrong.com.cn/api/v1/cjPush',
            'api_name' => "金榕新盘API",
            'rule_json' => '[{"orig":"clue_name","curr":"name","describe":""}]',
            'api_key' => "CommonClue"
        ],
    ];
    public function _initialize()
    {
        parent::_initialize();
    }

    //刷新生效时间
    public function batchUpdate(){


//        $list=Db::name('merchant')->select();
//        $user=Db::name('admin')->field('id,realname')->where('id','>',8)->select();
//        foreach ($list as $v){
//            $update=[];
//            if(!empty($v['bind_user'])){
//                foreach ($user as $vv){
//                    if($v['bind_user']==$vv['realname']){
//                        $update['bind_aid']=$vv['id'];
//                    }
//                }
//            }
//            if(!empty($v['weihu_user'])){
//                foreach ($user as $vv){
//                    if($v['weihu_user']==$vv['realname']){
//                        $update['weihu_aid']=$vv['id'];
//                    }
//                }
//            }
//            if(!empty($update)){
//                Db::name('merchant')->where('id',$v['id'])->update($update);
//            }
//        }
//        echo 1;


//        $log = Db::name('clue_log')
//            ->whereOr(function($query){
//                $query->where(['phone'=>123,'mer_id'=>312]);
//            })
////            ->whereOr(['mer_id'=>321,'clue_name'=>'aa','city'=>'cc'])
//            ->whereOr(function($query){
//                $query->where(['clue_name'=>'aa','city'=>'cc']);
//            })
//            ->fetchSql()->find();
//        dump($log);die;
//
//        $list=Db::name('merchant')->select();
//        foreach ($list as $v){
//            if(!empty($v['timing'])){
//                $timeArr = explode(' - ',$v['timing']);
//                Db::name('merchant')->where('id',$v['id'])->update(['start_time'=>$timeArr[0],'end_time'=>$timeArr[1]]);
//            }
//        }
    }

    public function index()
    {

        $username = input('username','');
        $phone = input('phone','');
        $mer_name = input('mer_name','');
        $status = input('status','');
        $orderb = input('orderb','');
        $weihuname = input('weihu','');

        $map = [];
        if($username != ''){
            $map['username'] = $username;
        }
        if($phone != ''){
            $map['phone'] =$phone;
        }
        if($mer_name != ''){
            $map['mer_name'] = ['like','%'.$mer_name.'%'];
        }

        if($status != 0){
            $map['status'] = $status;
        }

        $orderDy='id desc';
        if(!empty($orderb)){
            if($orderb==1){
                $orderDy='balance asc';
            }elseif($orderb==2){
                $orderDy='balance desc';
            }
        }

        if(!empty($weihuname)){
            $map['bind_aid|weihu_aid']=$weihuname;
        }

        if(in_array($this->group_id,[4,5])){
            $map['bind_aid|weihu_aid']=$this->uid;
        }

        $infos = model('Merchant')->getInfosByMapLimit($map, '', false,$orderDy,70);

        $admin=Db::name('admin')->column('realname','id');

        $infoTemp = model('AuthGroupAccess')->alias('a')
            ->field('a.*,b.phone,b.realname')
        ->join('admin b','a.uid=b.id')
        ->where(function ($q){
            $q->where('a.group_id',4)->whereOr('a.group_id',5)->whereOr('a.group_id',1);
        })
//        ->where('a.group_id',4)
            ->where('b.delete_time',NULL)->select();

//        dump($infoTemp);die;
        foreach ($infos as &$v){
            if($v['bind_aid']>0){
                $v['yingru']=$admin[$v['bind_aid']] ?? "";
            }else{
                $v['yingru']='';
            }
            if($v['weihu_aid']>0){
                $v['weihu']=$admin[$v['weihu_aid']] ?? "" ;
            }else{
                $v['weihu']='';
            }

           $v['weekStr']='';
            $weekEnd=[];
            if(!empty($v['weekday'])){
                $weekArr=explode(',',$v['weekday']);
                foreach ($weekArr as $vv){
                    if($vv==1){
                        $weekEnd[]='星期一';
                    }elseif ($vv==2){
                        $weekEnd[]='星期二';
                    }elseif ($vv==3){
                        $weekEnd[]='星期三';
                    }elseif ($vv==4){
                        $weekEnd[]='星期四';
                    }elseif ($vv==5){
                        $weekEnd[]='星期五';
                    }elseif ($vv==6){
                        $weekEnd[]='星期六';
                    }elseif ($vv==0){
                        $weekEnd[]='星期日';
                    }
                }
                $v['weekStr']=implode(',',$weekEnd);
            }

        }


        return $this->fetch('',[
            'infos' => $infos,
            'mer_name' => $mer_name,
            'username' => $username,
            'phone' => $phone,
            'status' => $status,
            'orderb' => $orderb,
            'group_id' => $this->group_id,
            'infoTemp' => $infoTemp,
            'weihuname' => $weihuname,
            'stsyem' => $this->push_system_type,
        ]);
    }


    public function moneyLog()
    {

        $mer_id = input('mer_id','');
        $times = input('times','');
        $type = input('type','');


        $map['mer_id'] = $mer_id;
        if(!empty($times)){
            $time_arr = explode(' - ',$times);
            $map['a.create_time'] = ['between',[strtotime($time_arr[0]),strtotime($time_arr[1].' 23:59:59')]];
        }
        if(!empty($type)){
            $map['type']=$type;
        }

        $orderDy='id desc';



        $infos = model('MerchantBalanceLog')->getInfosByMap($map, '', false);

//        dump($infoTemp);die;
        foreach ($infos as &$v){
            if($v['change_type']==1){
                $v['change']='加';
            }else{
                $v['change']='减';
            }
            if($v['type']==1){//1账户币2真实币3服务币
                $v['type_desc']='账户币';
            }elseif ($v['type']==2){
                $v['type_desc']='真实币';
            }elseif ($v['type']==3){
                $v['type_desc']='服务币';
            }

        }


        return $this->fetch('',[
            'infos' => $infos,
            'times' => $times,
            'type' => $type,

        ]);
    }
    

    public function edit()
    {
        $id = input('id');
        if(!$id) return self::showReturnCode(1002,'id 错误');
        $user = model('Merchant')->getInfoByMap(['id'=>$id]);
        $user['start_time'] = '';
        $user['end_time'] = '';
        if($user['timing'] != ''){
            $times = explode(' - ',$user['timing']);
            $user['start_time'] = $times[0];
            $user['end_time'] = $times[1];
        }
        return self::showJsonReturnCodeData('1001',$user,'');
    }

    public function edit_mapping()
    {
        $mer_id = input('mer_id');
        if(!$mer_id) return self::showReturnCode(1002,'mer_id 错误');
        $info = model('Mapping')->getInfoByMap(['mer_id'=>$mer_id]);
        if($info){
            $info['rules'] = json_decode($info['rule_json'], true);
            return self::showJsonReturnCodeData('1001',$info,'');
        }else{
            return self::showJsonReturnCodeData('1000','','');
        }

    }

    public function save()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                $save_data = input('post.');

                if(isset($id) && $id){
                    unset($save_data['push_system_type']);
                    $save_data['id'] = $id;
                    $isData=model('Merchant')->where('username',$save_data['username'])->find();
                    if($isData&&$isData['id']!=$id){
                        return self::showReturnCode(1011,'商户账号已存在');
                    }
                }else{
                    $save_data['status'] = 2; // 新增商户默认禁用

                    $isData=model('Merchant')->where('username',$save_data['username'])->find();
                    if($isData){
                        return self::showReturnCode(1011,'商户账号已存在');
                    }

                    unset($save_data['id']);
                }

                if(in_array($this->group_id,[4,5])){
                    $save_data['bind_aid']=$this->uid;
                    $save_data['weihu_aid']=$this->uid;
                }

                if(isset($save_data['is_sub_mer'])&&$save_data['is_sub_mer']=='on'){
                    $save_data['is_sub_mer']=1;
                }else{
                    $save_data['is_sub_mer']=0;
                }

                if(isset($save_data['is_send_phone'])&&$save_data['is_send_phone']=='on'){
                    $save_data['is_send_phone']=1;
                }else{
                    $save_data['is_send_phone']=0;
                }

                $result = $this->editData(false,'','Merchant',$save_data);
                if($result['code'] == 1001){
                    if(isset($id) && $id){
                        $result['msg'] = '修改商户成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'修改商户【'.$save_data['mer_name'].'】成功');
                    }else{
                        $merch_id = \db('merchant')->getLastInsID();
                        if (!empty($save_data['push_system_type'])) {
                            $push_system_data = [];
                            if ($save_data['push_system_type'] == self::PUSH_SYSTEM_MIAOYAN) {
                                $push_system_data = $this->push_system_mapping[self::PUSH_SYSTEM_MIAOYAN];
                            } elseif ($save_data['push_system_type'] == self::PUSH_SYSTEM_ZHANGDALONG) {
                                $push_system_data = $this->push_system_mapping[self::PUSH_SYSTEM_ZHANGDALONG];
                            }

                            if (!empty($push_system_data)) {
                                $time = time();
                                $save_data_mapping = [
                                    'mer_id' => $merch_id,
                                    'create_time' => $time,
                                    'update_time' => $time,
                                ];

                                $save_data_mapping = array_merge($save_data_mapping, $push_system_data);

                                model('Mapping')->allowField(true)->save($save_data_mapping);
                            }

                        }

                        $result['msg'] = '添加商户成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'添加商户【'.$save_data['mer_name'].'】成功');
                    }
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function saveRemark()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                $save_data = input('post.');

//                if(isset($id) && $id){
                    $save_data['id'] = $id;
                    $isData=model('Merchant')->where('id',$id)->find();
                    if($isData&&$isData['id']!=$id){
                        return self::showReturnCode(1011,'商户账号已存在');
                    }
//                }else{
//                    $save_data['status'] = 2; // 新增商户默认禁用
//
//                    $isData=model('Merchant')->where('username',$save_data['username'])->find();
//                    if($isData){
//                        return self::showReturnCode(1011,'商户账号已存在');
//                    }
//
//                    unset($save_data['id']);
//                }

//                if(in_array($this->group_id,[4,5])){
//                    $save_data['bind_aid']=$this->uid;
//                    $save_data['weihu_aid']=$this->uid;
//                }
//
//                if(isset($save_data['is_sub_mer'])&&$save_data['is_sub_mer']=='on'){
//                    $save_data['is_sub_mer']=1;
//                }else{
//                    $save_data['is_sub_mer']=0;
//                }
//
//                if(isset($save_data['is_send_phone'])&&$save_data['is_send_phone']=='on'){
//                    $save_data['is_send_phone']=1;
//                }else{
//                    $save_data['is_send_phone']=0;
//                }

                $result = $this->editData(false,'','Merchant',$save_data);
                if($result['code'] == 1001){
//                    if(isset($id) && $id){
                        $result['msg'] = '保存成功';
                        $this->RecordSystemLog($this->uid,$this->behavior,'保存成功');
//                    }else{
//                        $result['msg'] = '添加商户成功';
//                        $this->RecordSystemLog($this->uid,$this->behavior,'添加商户【'.$save_data['mer_name'].'】成功');
//                    }
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function save_timing()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                $save_data = input('post.');

                if($save_data['start_time'] == '' || $save_data['end_time'] == ''){
                    return self::showReturnCode(1012,'时间不能为空');
                }

//                if(strtotime($save_data['start_time']) < time()){
//                    return self::showReturnCode(1013,'开始时间必须晚于系统时间');
//                }

                if($save_data['start_time'] > $save_data['end_time']){
                    return self::showReturnCode(1014,'结束时间必须晚于开始时间');
                }

                $save_data['timing'] = $save_data['start_time'].' - '.$save_data['end_time'];

                $result = $this->editData(false,'','Merchant',$save_data);
                if($result['code'] == 1001){
                    $result['msg'] = '定时投放设置成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'商户【'.$id.'】的定时投放设置成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    /**
     * 时段
     * @return array
     */
    public function save_timeday()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id');
                $save_data = input('post.');

//                if($save_data['timeday'] == ''){
//                    return self::showReturnCode(1012,'时间不能为空');
//                }

                if (isset($save_data['wday'])){
                    $save_data['weekday']=implode(',',$save_data['wday']);
                }

//                if(strtotime($save_data['start_time']) < time()){
//                    return self::showReturnCode(1013,'开始时间必须晚于系统时间');
//                }

                $result = $this->editData(false,'','Merchant',$save_data);
                if($result['code'] == 1001){
                    $result['msg'] = '设置成功';
                    $this->RecordSystemLog($this->uid,$this->behavior,'商户【'.$id.'】的投放时段设置成功');
                }

                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function save_timing2()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id/a');
                $save_data = input('post.');

                if(empty($id)){
                    return self::showReturnCode(1012,'请勾选需要设置的商户');
                }
                if($save_data['start_time'] == '' || $save_data['end_time'] == ''){
                    return self::showReturnCode(1012,'时间不能为空');
                }

//                if(strtotime($save_data['start_time']) < time()){
//                    return self::showReturnCode(1013,'开始时间必须晚于系统时间');
//                }

                if($save_data['start_time'] > $save_data['end_time']){
                    return self::showReturnCode(1014,'结束时间必须晚于开始时间');
                }

                $save_data['timing'] = $save_data['start_time'].' - '.$save_data['end_time'];

                foreach ($id as $v){

                    $dbData[]=['id'=>$v,'timing'=>$save_data['timing'],'start_time'=>$save_data['start_time'],'end_time'=>$save_data['end_time']];
                }
                $result = model('Merchant')->saveAll($dbData);
                $this->RecordSystemLog($this->uid,$this->behavior,'商户'.implode(',',$id).'定时投放设置成功');

                return self::showReturnCode(1001,'定时投放设置成功');
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function save_timeday2()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id/a');
                $save_data = input('post.');


                if(empty($id)){
                    return self::showReturnCode(1012,'请勾选需要设置的商户');
                }
                if($save_data['timeday'] == ''){
                    return self::showReturnCode(1012,'时间不能为空');
                }

                if (isset($save_data['wday'])){
                    $save_data['weekday']=implode(',',$save_data['wday']);
                }else{
                    $save_data['weekday']='';
                }


                foreach ($id as $v){
                    $dbData[]=['id'=>$v,'timeday'=>$save_data['timeday'],'weekday'=>$save_data['weekday']];
                }
                $result = model('Merchant')->saveAll($dbData);

                $this->RecordSystemLog($this->uid,$this->behavior,'商户'.implode(',',$id).'投放时段设置成功');

                return self::showReturnCode(1001,'设置成功');

            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }


    public function save_mapping()
    {
        if(request()->isAjax()){
            try{

                $mer_id = input('post.mer_id');
                $params = input('post.','','trim');
                $save_data['mer_id'] = $params['mer_id'];
                $save_data['api_name'] = $params['api_name'];
                $save_data['api_url'] = $params['api_url'];
                $save_data['api_key'] = $params['api_key'];
                $rule = [];

                if($params['clue_name'] != ''){
                    $rule[] = ['orig'=>'clue_name','curr'=>$params['clue_name'],'describe'=>$params['clue_name*mapping']];
                }
                if($params['clue_type'] != ''){
                    $rule[] = ['orig'=>'clue_type','curr'=>$params['clue_type'],'describe'=>$params['clue_type*mapping']];
                }
                if($params['age'] != ''){
                    $rule[] = ['orig'=>'age','curr'=>$params['age'],'describe'=>$params['age*mapping']];
                }
                if($params['phone'] != ''){
                    $rule[] = ['orig'=>'phone','curr'=>$params['phone'],'describe'=>$params['phone*mapping']];
                }
                if($params['wechat'] != ''){
                    $rule[] = ['orig'=>'wechat','curr'=>$params['wechat'],'describe'=>$params['wechat*mapping']];
                }
                if($params['qq'] != ''){
                    $rule[] = ['orig'=>'qq','curr'=>$params['qq'],'describe'=>$params['qq*mapping']];
                }
                if($params['gender'] != ''){
                    $rule[] = ['orig'=>'gender','curr'=>$params['gender'],'describe'=>$params['gender*mapping']];
                }
                if($params['city'] != ''){
                    $rule[] = ['orig'=>'city','curr'=>$params['city'],'describe'=>$params['city*mapping']];
                }
                if($params['email'] != ''){
                    $rule[] = ['orig'=>'email','curr'=>$params['email'],'describe'=>$params['email*mapping']];
                }
                if($params['site_url'] != ''){
                    $rule[] = ['orig'=>'site_url','curr'=>$params['site_url'],'describe'=>$params['site_url*mapping']];
                }
                if($params['page_id'] != ''){
                    $rule[] = ['orig'=>'page_id','curr'=>$params['page_id'],'describe'=>$params['page_id*mapping']];
                }
                if($params['page_name'] != ''){
                    $rule[] = ['orig'=>'page_name','curr'=>$params['page_name'],'describe'=>$params['page_name*mapping']];
                }
                if($params['campaign_name'] != ''){
                    $rule[] = ['orig'=>'campaign_name','curr'=>$params['campaign_name'],'describe'=>$params['campaign_name*mapping']];
                }
                if($params['adgroup_name'] != ''){
                    $rule[] = ['orig'=>'adgroup_name','curr'=>$params['adgroup_name'],'describe'=>$params['adgroup_name*mapping']];
                }
                if($params['unit_name'] != ''){
                    $rule[] = ['orig'=>'unit_name','curr'=>$params['unit_name'],'describe'=>$params['unit_name*mapping']];
                }
                if($params['creative_name'] != ''){
                    $rule[] = ['orig'=>'creative_name','curr'=>$params['creative_name'],'describe'=>$params['creative_name*mapping']];
                }
                if($params['ad_name'] != ''){
                    $rule[] = ['orig'=>'ad_name','curr'=>$params['ad_name'],'describe'=>$params['ad_name*mapping']];
                }
                if($params['search_term'] != ''){
                    $rule[] = ['orig'=>'search_term','curr'=>$params['search_term'],'describe'=>$params['search_term*mapping']];
                }
                if($params['keyword'] != ''){
                    $rule[] = ['orig'=>'keyword','curr'=>$params['keyword'],'describe'=>$params['keyword*mapping']];
                }
                if($params['clue_local'] != ''){
                    $rule[] = ['orig'=>'clue_local','curr'=>$params['clue_local'],'describe'=>$params['clue_local*mapping']];
                }
                if($params['ip'] != ''){
                    $rule[] = ['orig'=>'ip','curr'=>$params['ip'],'describe'=>$params['ip*mapping']];
                }
                if($params['house'] != ''){
                    $rule[] = ['orig'=>'house','curr'=>$params['house'],'describe'=>$params['house*mapping']];
                }
                if($params['car'] != ''){
                    $rule[] = ['orig'=>'car','curr'=>$params['car'],'describe'=>$params['car*mapping']];
                }
                if($params['loan_limit'] != ''){
                    $rule[] = ['orig'=>'loan_limit','curr'=>$params['loan_limit'],'describe'=>$params['loan_limit*mapping']];
                }
                if($params['public_funds'] != ''){
                    $rule[] = ['orig'=>'public_funds','curr'=>$params['public_funds'],'describe'=>$params['public_funds*mapping']];
                }
                if($params['company'] != ''){
                    $rule[] = ['orig'=>'company','curr'=>$params['company'],'describe'=>$params['company*mapping']];
                }
                if($params['apply_limit'] != ''){
                    $rule[] = ['orig'=>'apply_limit','curr'=>$params['apply_limit'],'describe'=>$params['apply_limit*mapping']];
                }
                if($params['remark'] != ''){
                    $rule[] = ['orig'=>'remark','curr'=>$params['remark'],'describe'=>$params['remark*mapping']];
                }
                if($params['source'] != ''){
                    $rule[] = ['orig'=>'source','curr'=>$params['source'],'describe'=>$params['source*mapping']];
                }

                if(empty($rule)){
                    return self::showReturnCode(1003,'映射字段不能为空');
                }

                $save_data['rule_json'] = json_encode($rule, JSON_UNESCAPED_UNICODE);

                $info = model('Mapping')->getInfoByMap(['mer_id'=>$mer_id]);

                if($info){
                    model('Mapping')->where(['mer_id'=>$mer_id])->update($save_data);
                }else{
                    model('Mapping')->allowField(true)->save($save_data);
                }

                $this->RecordSystemLog($this->uid,$this->behavior,'商户【'.$mer_id.'】的接收设置成功');
                $result['code'] = 1001;
                $result['msg'] = '接收设置成功';
                return $result;
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    public function status()
    {
        if($this->request->isAjax()){
            $id = input('post.id');

         /*   开关开启，必须同时满足以下条件：
            1、设置定时投放后，可开启
            2、设置接收设置后，可开启
            3、设置分发规则后，可开启
         */
            if(input('post.status') == 1){
//                $mer = Db::name('merchant')->find($id);
//                if($mer['timing'] == ''){
//                    return $this->showReturnCode(1011,'请先设置定时投放时间');
//                }

                $push=model('Push')->where('mer_id',$id)->where('status',1)->find();
                if(empty($push)){
                    return $this->showReturnCode(1011,'请先设置定时投放时间');
                }

                $mapp = Db::name('mapping')->where(['mer_id'=>$id])->find();
//                if(!$mapp){
//                    return $this->showReturnCode(1011,'请先设置接收设置');
//                }

                $push = model('Push')->getListByMap(['mer_id'=>$id]);
                if(!$push){
                    return $this->showReturnCode(1011,'请先设置分发规则');
                }
            }

            $res = model('Merchant')->save(['status'=>input('post.status')],['id'=>$id]);

            if (input('post.status') == 1) {
                (new PushRecord())->addByMerchs([$id]); //判断是否需要增加分发规则生效记录
            }

            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'状态操作成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'操作失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

    public function batchstatus()
    {
        if(request()->isAjax()){
            try{

                $id = input('post.id/a');
                $save_data = input('post.');

                if(empty($id)){
                    return self::showReturnCode(1012,'请勾选需要设置的商户');
                }

                if ($save_data['status'] == 1) {
                    (new PushRecord())->addByMerchs($id); //判断是否需要增加分发规则生效记录
                }

                $result = model('Merchant')->whereIn('id',$id)->update(['status'=>$save_data['status']]);
                $this->RecordSystemLog($this->uid,$this->behavior,'商户'.implode(',',$id).'设置'.$save_data['status'].'成功');

                return self::showReturnCode(1001,'设置成功');
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return self::showReturnCode(1011,$e->getMessage());
            }
        }else{
            return self::showReturnCode(1002);
        }
    }

    //发送短信
    public function sendSmsPhone(){

        if($this->request->isAjax()){
            $id = input('post.id');


            $mer = Db::name('merchant')->find($id);
            $sendPhone=$mer['phone'];
            if($sendPhone){
                $mobiles=$sendPhone;
                $content='【'.config('database')['host_sms_name']."】提醒你有个线索查看！";
                $extno='';
                $sendtime='';
//                $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
//                $result = json_decode(json_encode(simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
//                if($result['returnstatus']=='Success'&&$result['successCounts']>0){
//                    $this->RecordSystemLog($this->uid,$this->behavior,'短信发送成功,操作ID: '.$id);
//                    return $this->showReturnCode(1001,$result['message']);
//                }else{
//                    return $this->showReturnCode(1009,$result['message']);
//                }
                $res=SmsMuSend::send($mobiles,$content);

                $xmlObject = simplexml_load_string($res);
                $json = json_encode($xmlObject);
                $res = json_decode($json, true);

                if(!empty($res)){
//                    $res=json_decode($res,true);
                    if($res['returnstatus']=='Success'){
                        $this->RecordSystemLog($this->uid,$this->behavior,'短信发送成功,操作ID: '.$id);
                        return $this->showReturnCode(1001,'短信发送成功');
                    }else{
                        $this->RecordSystemLog($this->uid,$this->behavior,'短信发送失败'.$res['message'].',操作ID: '.$id);
                        return $this->showReturnCode(1009,$res['desc']);
                    }
                }else{
                    return $this->showReturnCode(1009,'短信发送失败');
                }
            }else{
                return $this->showReturnCode(1011,'商户没有联系手机');
            }

        }else{
            return $this->showReturnCode(1002);
        }
//        $sendPhone='15052442268';
//        if($sendPhone){
//            $mobiles=$sendPhone;
//            $content='【'.config('database')['host_sms_name'].'】提醒你有个线索查看！';
//            $extno='';
//            $sendtime='';
//            $res=MessageSend::send($mobiles,$extno,$content,$sendtime);
//        }
//        dump($res);die;
    }

    /**
     * 软删除
     */
    public function delete()
    {
        if($this->request->isAjax()){
            $id = input('post.id');
            $model = $this->request->controller();
            $infoTemp = model($model)->getInfoByMap('','','',false);
            if(isset($infoTemp['parent_id'])){
                $infosCount = model($model)->countNum(['parent_id'=>$id],false); // 查询子分类数量
                if($infosCount > 0)  return $this->showReturnCode(1009,'该分类下有子分类,请批量删除');
            }
            $res = model($model)->destroy($id);

              model('Push')->destroy(['mer_id'=>$id]);

            if($res){
                $this->RecordSystemLog($this->uid,$this->behavior,'删除成功,操作ID: '.$id);
                return $this->showReturnCode(1001);
            }else{
                return $this->showReturnCode(1009,'删除失败');
            }
        }else{
            return $this->showReturnCode(1002);
        }
    }

}